<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="searchOptions.staffId" placeholder="工号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="searchOptions.tel" placeholder="手机号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="searchOptions.nickName" placeholder="姓名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>

      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>

      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>
    <!-- {{ searchOptions }} -->

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      stripe
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="序号" type="index" align="center" width="80" />

      <el-table-column label="服务名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.appointName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="服务描述" show-overflow-tooltip align="center">
        <template slot-scope="{row}">
          <span>{{ row.appointDesc }}</span>
        </template>
      </el-table-column>

      <el-table-column label="服务地点" show-overflow-tooltip align="center">
        <template slot-scope="{row}">
          <span>{{ row.appointAddr }}</span>
        </template>
      </el-table-column>

      <el-table-column label="联系电话" align="center">
        <template slot-scope="{row}">
          <span>{{ row.appointTel }}</span>
        </template>
      </el-table-column>

      <el-table-column label="营业时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.appointTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="图片显示" align="center">
        <template slot-scope="{row}">
          <el-image
            :src="row.fileUrl"
            :zoom-rate="1.2"
            :preview-src-list="[row.fileUrl]"
            :initial-index="0"
            style="width: 85px;height: 85px;"
            fit="cover"
          />

        </template>
      </el-table-column>

      <el-table-column show-overflow-tooltip label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="success" size="mini" @click="handleInfo(row)">
            数据
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 30px;" />
    <!-- <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" /> -->
    <!-- {{ total }} {{ listQuery }} -->

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <!-- {{ temp }} -->
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">

        <el-form-item label="服务名称" prop="appointName">
          <el-input v-model="temp.appointName" :placeholder="'请填写服务名称'" />
        </el-form-item>

        <el-form-item
          label="服务描述"
          prop="appointDesc"
        >
          <el-input
            v-model="temp.appointDesc"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea"
            maxlength="20"
            show-word-limit
            :placeholder="'请填写服务描述'"
          />
        </el-form-item>

        <el-form-item label="营业地址" prop="appointAddr">
          <el-input v-model="temp.appointAddr" :placeholder="'请填写营业地址'" />
        </el-form-item>
        <el-form-item label="营业时间" prop="appointTime">
          <el-input v-model="temp.appointTime" :placeholder="'请填写营业时间'" />
        </el-form-item>
        <el-form-item label="联系电话" prop="appointTel">
          <el-input v-model="temp.appointTel" :placeholder="'请填写联系电话'" />
        </el-form-item>

        <el-form-item label="图片上传" prop="fileUrl">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :action="uploadUrl"
            :limit="1"
            :data="{
              fileName:temp.fileName,
              fileClassify:1,
              appointName:temp.appointName,
              appointDesc:temp.appointDesc,
              appointAddr:temp.appointAddr,
              appointTel:temp.appointTel,
              appointTime:temp.appointTime
            }"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-change="handleUploadChange"
            :on-exceed="handleExceed"
            :auto-upload="false"
          >
            <div class="image-container">
              <el-image
                v-if="temp.fileUrl"
                :src="temp.fileUrl"
                :zoom-rate="1.0"
                fit="cover"
                style="width: 85px;height: 85px;object-fit: cover;display: block;"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon" style="padding: 20px;" />

              <div v-if="temp.fileUrl" class="image-overlay">
                <i class="el-icon-edit" />
              </div>
            </div>
          </el-upload>
        </el-form-item>

        <!-- {{ temp }} -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="infoTitle" :visible.sync="dialogINFOFormVisible">

      <el-descriptions
        :column="4"
        title="数据详情"
        size="large"
      >

        <el-descriptions-item label="总订单数">{{ chartData.totalCount }}</el-descriptions-item>
        <el-descriptions-item label="已完成">{{ chartData.completedCount }}</el-descriptions-item>
        <!-- <el-descriptions-item label="处理中">{{ chartData.processingCount }}</el-descriptions-item> -->
        <el-descriptions-item label="更多数据">
          <el-button size="small" style="padding:4px 10px" @click="handleMoreInfo()">查看</el-button>
        </el-descriptions-item>

      </el-descriptions>
      <div style="margin-top: 10px;" />
      <el-descriptions
        :column="1"
        title="已完成数据"
        size="large"
      />
      <div style="margin-top: 10px;" />

      <line-chart :chart-data="lineChartData" />

      <div style="margin-top: 10px;" />
    </el-dialog>

  </div>
</template>

<script>
import { fetchAppoint, deleteAppoint, fetchAppointOrderData } from '@/api/appoint'
import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
// import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox } from 'element-ui'
import { validTime } from '@/utils/validate'
import LineChart from './components/LineChart'

export default {
  name: 'Ordermanager',
  components: { LineChart },
  directives: { waves },
  data() {
    const validateTime = (rule, value, callback) => {
      if (!validTime(value)) {
        callback(new Error('请输入正确的时间如9:00-15:00'))
      } else {
        callback()
      }
    }

    return {
      chartData: {
        completedCount: '',
        processingCount: '',
        totalCount: ''
      },
      lineChartData: { xlabel: [], completedCount: [] },
      uploadUrl: 'https://braincognitiontec.top:30005/appoint-info/upload-image',
      ori_data: null,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20
      },
      searchOptions: {
        staffId: '',
        tel: '',
        nickName: ''
      },
      showReviewer: false,
      temp: { fileUrl: '' },
      dialogFormVisible: false,
      dialogINFOFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
        info: '详情'
      },
      rules: {
        appointName: [{ required: true, message: '必填', trigger: 'change' }],
        appointDesc: [{ required: true, message: '必填', trigger: 'change' }],
        appointAddr: [{ required: true, message: '必填', trigger: 'change' }],
        appointTel: [{ required: true, message: '必填', trigger: 'change' }],
        appointTime: [{ required: true, trigger: 'change', validator: validateTime }]

      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchAppoint().then(response => {
        this.ori_data = response.data.data
        this.list = this.ori_data
        this.total = response.data.data.length
        setTimeout(() => {
          this.listLoading = false
        }, 0.6 * 1000)
      })
    },
    handleFilter() {
      const staffId = this.searchOptions.staffId
      const tel = this.searchOptions.tel
      const nickName = this.searchOptions.nickName

      let result = this.ori_data
      // console.log(result)
      if (staffId !== '') {
        result = result.filter(item => {
          // console.log(item)
          // console.log(staffId)
          if (item.tel !== undefined) {
            return (item.staffId.indexOf(staffId)) !== -1
          }
        })
      }

      if (tel !== '') {
        result = result.filter(item => {
          // console.log(item.tel, tel, typeof item.tel, typeof tel)
          if (item.tel !== undefined) {
            return (item.tel.indexOf(tel)) !== -1
          }
        })
      }

      if (nickName !== '') {
        result = result.filter(item => {
          if (item.tel !== undefined) {
            return (item.nickName.indexOf(nickName)) !== -1
          }
        })
      }
      // console.log(result)
      this.list = result
      this.total = result.length
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = { fileUrl: '' }
    },

    handleCreate() {
      this.resetTemp()
      this.temp.fileUrl = ''
      this.temp.fileName = '预约服务' + (this.total + 1)
      this.temp.createTime = new Date().toISOString().replace(/\.[\d]{3}Z/, '')

      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      if (this.temp.fileUrl === '') {
        this.$message.error('必须上传图片')
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$refs.upload.submit()
        }
      })
    },
    handleUpdate(row) {
      this.resetTemp()
      this.temp = { ...this.temp, ...row }
      console.log(this.temp)
      var a = this.temp.filePath.lastIndexOf('/')
      this.temp.fileName = this.temp.filePath.slice(a + 1)
      this.temp.fileTag = this.temp.fileName.slice(this.temp.fileName.lastIndexOf('.') + 1)
      this.temp.fileName = this.temp.fileName.slice(0, this.temp.fileName.lastIndexOf('.'))

      fetch(this.temp.fileUrl)
        .then(res => res.blob())
        .then(blob => {
          const newfile = new File([blob], `${this.temp.fileName}.${this.temp.fileTag}`, { type: this.temp.fileTag === 'png' ? 'image/png' : 'image/jpeg' })

          this.$refs.upload.handleStart(newfile)
        })
      // console.log('fileName', this.temp.fileName, 'filetag', this.temp.fileTag)

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      if (this.temp.fileUrl === '') {
        this.$message.error('必须上传图片')
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          deleteAppoint({ id: this.temp.id }).then(res => {
            this.$refs.upload.submit()
          })
        }
      })
    },
    handleDelete(row, index) {
      MessageBox.confirm('您将要删除该资源且无法复原,是否确定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAppoint({ id: row.id }).then(res => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      })
    },

    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['工号', '姓名', '手机号', '用户角色', '用户状态', '创建时间']
        const filterVal = ['staffId', 'nickName', 'tel', 'userRole', 'deleted', 'createTime']
        const data = this.formatJson(filterVal)
        // console.log(data)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-employees'
        })
        this.downloadLoading = false
      })
    },
    handleInfo(row, index) {
      this.resetTemp()
      this.temp = { ...this.temp, ...row }
      this.dialogINFOFormVisible = true

      fetchAppointOrderData({ 'appointName': this.temp.appointName }).then(response => {
        this.chartData = response.data.data
        this.lineChartData.xlabel = response.data.data.mouthCompletedOrderCountList.monthList
        this.lineChartData.completedCount = response.data.data.mouthCompletedOrderCountList.completedCountList
      })
    },
    handleMoreInfo() {
      this.$router.push({ path: `/appointmanager/appointorder?appointName=${this.temp.appointName}` })
    },
    // handleInfo(row) {
    //   this.resetTemp()
    //   this.temp = { ...this.temp, ...row }
    //   console.log(this.temp)
    //   this.$router.push({ path: `/appointmanager/appointorder?appointName=${this.temp.appointName}` })
    // },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j.split('.')[0] === 'detail') {
            // console.log(v['detail'][j.split('.')[1]])
            return v['detail'][j.split('.')[1]]
          } else {
            // console.log(v[j])
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    handleUploadChange(file, fileList) {
      file = file.raw
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
        return false
      }
      const isLt1M = file.size / 1024 / 1024 < 2
      if (!isLt1M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      const suffix = file.name.lastIndexOf('.')
      const fileTag = file.name.substring(suffix + 1)
      this.temp.fileTag = fileTag
      const url = URL.createObjectURL(file)
      this.temp.fileUrl = url
    },
    beforeUpload(file) {
      return true
    },
    handleUploadSuccess(response) {
      console.log('response', response)
      if (response.success === false) {
        this.$message.error(response.errorMsg || '上传失败!请重新上传')
      } else {
        this.$message.success('上传成功!')
        if (this.dialogStatus === 'create') {
          this.list.unshift(this.temp)
          this.$router.go(0)
        } else if (this.dialogStatus === 'update') {
          // this.$router.go(0)
          const index = this.list.findIndex(v => v.id === this.temp.id)
          this.list.splice(index, 1, this.temp)
          this.list[index].id = response.data.ApplointInfo.id
        }
        this.dialogFormVisible = false
      }
    },
    handleUploadError(res) {
      this.$message.error('上传失败!请重新上传')
    },
    handleExceed(files, fileList) {
      this.$set(fileList[0], 'raw', files[0])
      this.$set(fileList[0], 'name', files[0].name)
      this.$refs['upload'].clearFiles()// 清除文件
      this.$refs['upload'].handleStart(files[0])// 选择文件后的赋值方法
    }
  }}

</script>

<style lang="scss">
.image-container {
  position: relative;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.image-overlay i {
  font-size: 24px;
  color: #fff;
}
</style>
